import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
from typing import Optional
from conf.read_conf import read_conf
import logging

# # 基本配置，读取conf.ini
# DINGTALK_SECRET = 'SEC95a7ab06442784d48dafb01b4e2d944e487603c1691564fe80e1e02936cfd778'
# DINGTALK_ACCESS_TOKEN = '0621e8ec350e0829f7996f76513edd4ca53a91f1e1dac4613ec699c76e8a9e59'
# WEBHOOK_URL = "https://oapi.dingtalk.com/robot/send"
# AT_MOBILES = ["18933481388"]


def generate_dingtalk_signature(timestamp, secret):
    """生成钉钉机器人签名"""
    string_to_sign = f"{timestamp}\n{secret}"
    hmac_code = hmac.new(
        secret.encode('utf-8'),
        string_to_sign.encode('utf-8'),
        digestmod=hashlib.sha256
    ).digest()
    return urllib.parse.quote_plus(base64.b64encode(hmac_code))


def dingding(case_id, name, url, txt, result, at_mobiles=None):
    """
    发送钉钉机器人通知

    :param case_id: 用例编号
    :param name: 用例名称
    :param url: 接口地址
    :param txt: 错误信息
    :param result: 接口响应
    :param at_mobiles: 需要@的手机号列表
    :return: 是否发送成功
    """
    WEBHOOK_URL = read_conf('dingding','WEBHOOK_URL')
    DINGTALK_SECRET = read_conf('dingding', 'DINGTALK_SECRET')
    DINGTALK_ACCESS_TOKEN = read_conf('dingding', 'DINGTALK_ACCESS_TOKEN')
    AT_MOBILES = read_conf('dingding', 'AT_MOBILES')

    timestamp = str(round(time.time() * 1000))
    sign = generate_dingtalk_signature(timestamp, DINGTALK_SECRET)

    payload = {
        'access_token': DINGTALK_ACCESS_TOKEN,
        'timestamp': timestamp,
        'sign': sign
    }

    content = f"""❗测试不通过
听芝-用例编号：{case_id}
用例名称：{name}
接口地址：{url}
错误信息：{txt}
接口响应：{result}
请及时查看，跟进回复人:"""

    body = {
        "msgtype": "text",
        "text": {"content": content},
        "at": {
            "atMobiles": at_mobiles or AT_MOBILES,
            "isAtAll": False
        }
    }

    headers = {'Content-Type': 'application/json; charset=utf-8'}

    try:
        response = requests.post(
            WEBHOOK_URL,
            params=payload,
            headers=headers,
            json=body,
            verify=False,
            timeout=5
        )
        response.raise_for_status()
        return True
    except requests.exceptions.RequestException as e:
        logging.error(f"钉钉消息发送失败: {e}")
        return False

#
# # 使用示例
# if __name__ == "__main__":
#     dingding(
#         case_id="TC001",
#         name="用户登录接口测试",
#         url="/api/user/login",
#         txt="HTTP 500 服务器错误",
#         result="{'code': 500, 'message': 'Internal Server Error'}"
#     )